package com.example.jiradata.service;

import com.example.jiradata.jpa.JiraIssueTypeRepository;
import com.example.jiradata.jpa.JiraProjectIssueTypeRepository;
import com.example.jiradata.jpa.JiraProjectRepository;
import com.example.jiradata.pojo.JiraIssueType;
import com.example.jiradata.pojo.JiraProject;
import com.example.jiradata.pojo.JiraProjectIssueType;
import com.example.jiradata.utils.HttpClientUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;

@Service
@Transactional
public class JiraProjectIssueTypeService {

    @Autowired
    private HttpClientUtils httpClientUtils;

    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    private JiraProjectIssueTypeRepository jiraProjectIssueTypeRepository;
    @Autowired
    private JiraProjectRepository jiraProjectRepository;
    @Autowired
    private JiraIssueTypeRepository jiraIssueTypeRepository;

    public void syncProjectIssueType() throws IOException {
        String res = httpClientUtils.exchange("https://tngasia.atlassian.net/rest/api/2/project?expand=projectKeys,description,issueTypes,lead",new ParameterizedTypeReference<String>(){},null, HttpMethod.GET);
        System.out.println(res);

        List<JiraProject> jiraProjects = objectMapper.readValue(res, new TypeReference<List<JiraProject>>() {});
        for (JiraProject jiraP : jiraProjects) {
            jiraP.setLeadAccountId(jiraP.getLead()!=null?jiraP.getLead().getAccountId():null);
            System.out.println(jiraP.getJiraProjectId());
            for (JiraProject.IssueType issueType : jiraP.getIssueTypes()) {
                System.out.println("issueType id " + issueType.getId());
                JiraProject project = jiraProjectRepository.findByJiraProjectId(jiraP.getJiraProjectId());
                JiraIssueType jiraIssueType = jiraIssueTypeRepository.findByJiraIssueTypeId(issueType.getId());

                JiraProjectIssueType jiraProjectIssueType = new JiraProjectIssueType();
                jiraProjectIssueType.setProjectId(project.getId());
                jiraProjectIssueType.setIssueTypeId(jiraIssueType.getId());
                jiraProjectIssueTypeRepository.save(jiraProjectIssueType);
            }
        }
    }

}
